package com.pks.datacenter.controller.basic;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.pks.datacenter.aspect.AspectLogTag;
import com.pks.datacenter.config.RedisKeyConfig;
import com.pks.datacenter.dto.CascaderDto;
import com.pks.datacenter.entity.basic.Tag;
import com.pks.datacenter.handler.RedisHandler;
import com.pks.datacenter.service.basic.TagService;
import com.pks.resultful.common.SRemoteResult;
import com.pks.util.UtilConvert;
import com.pks.util.UtilString;
import com.pks.web.springmvc.controller.BasicController;


@RestController
@RequestMapping(value = "/tag")
@Scope("prototype")
@Component("tagController")
@Api(tags = "标签库")
public class TagController extends BasicController {

	@Resource
	private TagService tagService;
	@Resource
	private RedisHandler redisHandler;

	@AspectLogTag(operType = "删除")
	@ApiOperation(value = "删除记录")
	@RequestMapping(value = "/delete" , method = RequestMethod.POST)
	public SRemoteResult<String> delete(HttpServletRequest request, String ids) {
		if (UtilString.isBlank(ids)) {
			return SRemoteResult.initErrorParamBlank(null);
		}
		if (StringUtils.isBlank(ids) || !ids.matches("^[0-9]+(,[0-9]+)*$")) {
			return SRemoteResult.initErrorParamInvalid(null);
		}
		List<Long> idList = UtilConvert.string2LongList(ids);
		if (tagService.getTotalRows(tagService.initQbuilder("pids", idList)) > 0) {
			return SRemoteResult.initError("要删除的列表中存在下级标签，无法删除");
		}
		if (idList.size() == 1) {
			tagService.delete(idList.get(0));
		} else {
			tagService.deleteByIds(idList);
		}
		Iterator<Map.Entry<Integer,String>> iterator = Tag.TYPE_MAP.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<Integer,String> entry = iterator.next();
            redisHandler.del(RedisKeyConfig.KEY_LIST_TAGS_PREFIX + entry.getKey());
        }
		return SRemoteResult.initSuccess(null);
	}
	
	@AspectLogTag(operType = "修改")
	@ApiOperation(value = "新增或修改")
	@RequestMapping(value = "/modify" , method = RequestMethod.POST)
	public SRemoteResult<String> modify(HttpServletRequest request, Tag obj) {
		if (obj == null) {
			return SRemoteResult.initErrorParamMissing(null);
		}
		if (obj.getType() == null || !Tag.TYPE_MAP.containsKey(obj.getType())) {
			return SRemoteResult.initError("没有该类型的标签");
		}
		if (obj.getState() == null || (obj.getState() != 1 && obj.getState() != 0)) {
			return SRemoteResult.initError("请选择标签状态");
		}
		if (obj.getId() == null) {
			obj.insertBefore();
			tagService.insert(obj);
		} else {
			Tag update = tagService.findById(obj.getId());
			if (update == null) {
				return SRemoteResult.initErrorDataNone();
			}
			if (obj.getState() == 0) {
				if (tagService.getTotalRows(tagService.initQbuilder(new String[]{"pid","state"}, new Object[]{obj.getId(),1})) > 0) {
					return SRemoteResult.initError("该标签下还有其他正在使用的标签 ，无法关闭");
				}
			}
			tagService.update(obj);
		}
		redisHandler.del(RedisKeyConfig.KEY_LIST_TAGS_PREFIX + obj.getType());
		return SRemoteResult.initSuccess(null);
	}

	@ApiOperation(value = "获取详情")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "id",value = "id", dataType = "long" , paramType = "query" )
	})
	@RequestMapping(value = "/get" , method = RequestMethod.GET)
	public SRemoteResult<Tag> findInfo(HttpServletRequest request, Long id) {
		if (id == null) {
			return SRemoteResult.initErrorParamMissing(null);
		}
		Tag obj = tagService.findById(id);
		if (obj == null) {
			return SRemoteResult.initErrorDataNone();
		}
		return SRemoteResult.initSuccess(obj);
	}

	@ApiOperation(value = "列表查询")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "type",value = "标签类型(1-数据源标签 2-接口标签 3-接口账号标签)", dataType = "Integer" , paramType = "query" )
		,@ApiImplicitParam(name = "pid",value = "上级ID", dataType = "Long" , paramType = "query" )
		,@ApiImplicitParam(name = "name",value = "标签名称", dataType = "String" , paramType = "query" )
		,@ApiImplicitParam(name = "nameLike",value = "标签名称", dataType = "String" , paramType = "query" )
		,@ApiImplicitParam(name = "offset",value = "分页起始页（默认0）", dataType = "int" , paramType = "query" )
		,@ApiImplicitParam(name = "pagesize",value = "分页每页行数（默认10）", dataType = "int" , paramType = "query" )
	})
	@RequestMapping(value = "/list" , method = RequestMethod.POST)
	public SRemoteResult<List<Tag>> list(HttpServletRequest request,Integer type,Long pid,String name ,String nameLike  ,Integer offset,Integer pagesize) {
		Map<String, Object> qbuilder = new HashMap<String, Object>();
		if (type != null) {
			qbuilder.put("type", type);
		}
		if (pid != null) {
			qbuilder.put("pid", pid);
		}
		if (UtilString.isNotBlank(name)) {
			qbuilder.put("name", name);
		}
		if (UtilString.isNotBlank(nameLike)) {
			qbuilder.put("nameLike", "%" + nameLike.trim() + "%");
		}
		List<Tag> list = new ArrayList<Tag>();
		int total = 0;
		total = tagService.getTotalRows(qbuilder);
		if (total > 0) {
			list = tagService.findByPage(null, qbuilder);
		}
		return SRemoteResult.initPageList(list, total);
	}


    @ApiOperation(value = "数据查询（不分页）")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "type",value = "标签类型(1-数据源标签 2-接口标签 3-接口账号标签)", dataType = "Integer" , paramType = "query" )
		,@ApiImplicitParam(name = "pid",value = "上级ID", dataType = "Long" , paramType = "query" )
		,@ApiImplicitParam(name = "name",value = "标签名称", dataType = "String" , paramType = "query" )
		,@ApiImplicitParam(name = "nameLike",value = "标签名称", dataType = "String" , paramType = "query" )
	    })
    @RequestMapping(value = "/data" , method = RequestMethod.POST)
    public SRemoteResult<List<Tag>> data(HttpServletRequest request,Integer type,Long pid,String name ,String nameLike  ) {
        Map<String, Object> qbuilder = new HashMap<String, Object>();
        if (type != null) {
            qbuilder.put("type", type);
        }
        if (pid != null) {
            qbuilder.put("pid", pid);
        }
        if (UtilString.isNotBlank(name)) {
            qbuilder.put("name", name);
        }
        if (UtilString.isNotBlank(name)) {
            qbuilder.put("name", "%" + name + "%");
        }
        List<Tag> list = new ArrayList<Tag>();
        list = tagService.find(null, qbuilder, null);
        return SRemoteResult.initPageList(list, null);
    }

    @ApiOperation(value = "级联数据")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "type",value = "标签类型(1-数据源标签 2-接口标签 3-接口账号标签)",required = true, dataType = "Integer" , paramType = "query" )
	    })
    @RequestMapping(value = "/cascadeList" , method = RequestMethod.POST)
    public SRemoteResult<List<CascaderDto>> cascadeList(HttpServletRequest request,Integer type ) {
    	List<CascaderDto> result = new ArrayList<CascaderDto>();
    	if (type != null) {
    		Map<String, Object> qbuilder = new HashMap<String, Object>();
    		qbuilder.put("type", type);
//    		List<Tag> list = tagService.find("orders asc", qbuilder, null);
    		List<Tag> list = tagService.findByType(type);
    		for (Tag tag : list) {
    			result.add(new CascaderDto(tag.getId(), tag.getPid(), String.valueOf(tag.getId()), tag.getName()));
    		}
    		result = CascaderDto.convertTree(result);
    	}
        
        return SRemoteResult.initPageList(result, null);
    }
    
    

}
